package cybercode.carsaleserver.controller.interceptor;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.math.BigDecimal;
import java.util.List;


/**
 * 踩坑：如果有多个继承WebMvcConfigurationSupport的设置类，只有一个会生效。
 */
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
//    @Value("${cross-origin.prod}")
//    private String prodUrl;
//
//    @Value("${cross-origin.dev}")
//    private String devUrl;
//
//    @Value("${cross-origin.enable}")
//    private boolean enableCross;

    private final TokenInterceptor tokenInterceptor;


    public WebConfig(TokenInterceptor tokenInterceptor) {
        this.tokenInterceptor = tokenInterceptor;
    }


    /**
     * 拦截器适用路径配置
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor).addPathPatterns("/**");
        super.addInterceptors(registry);
    }


//    /**
//     * 存在自定义拦截器时，该配置会被覆盖而不生效。在自定义拦截器中配置返回头来解决，这里即自定义的TokenInterceptor
//     * @param registry
//     */
//    @Override
//    protected void addCorsMappings(CorsRegistry registry) {
//
//        System.out.println("Set cors mapping...");
//
//        if (enableCross) {
//            registry.addMapping("/**")
//                    .allowedOriginPatterns(devUrl)
//                    .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
//                    .allowCredentials(true)
//                    .maxAge(3600)
//                    .allowedHeaders("*");
//            super.addCorsMappings(registry);
//        } else {
//            registry.addMapping("/**")
//                    .allowedOrigins(prodUrl)
//                    .allowCredentials(true)
//                    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
//                    .maxAge(3600);
//        }
//    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
//        objectMapper.setPropertyNamingStrategy(new PropertyNamingStrategies.UpperCamelCaseStrategy());
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        /**
         * 序列换成json时,将所有的long变成string
         * js的数字类型精度不够，long型数字无法全部转换
         */
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        simpleModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);

        objectMapper.registerModule(simpleModule);
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);

        //放到第一个, 否则默认converter会先生效
        converters.add(0, jackson2HttpMessageConverter);
    }


//    /**
//     * 静态资源配置
//     */
//    @Override
//    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
//        registry.addResourceHandler("/static/**")
//                .addResourceLocations("classpath:/META-INF/resources/")
//                .addResourceLocations("classpath:/resources/")
//                .addResourceLocations("classpath:/static/")
//                .addResourceLocations("classpath:/public/");
////        registry.addResourceHandler("/image/**").addResourceLocations("file:" + PathUtil.baseImagesPath);
////        registry.addResourceHandler("/word/**").addResourceLocations("file:" + PathUtil.baseWordPath);
////        registry.addResourceHandler("/excel/**").addResourceLocations("file:" + PathUtil.baseExcelPath);
//        super.addResourceHandlers(registry);
//    }
}
